<template>
  <div>
    <a-alert message="用工单位数据来源于企业 账户管理-用工单位" type="info" show-icon class="mb16" />
    <a-spin :spinning="spinning">
      <div class="employee-selector-wrapper2">
        <div>
          <div class="employee-selector-block">
            <a-input-search placeholder="搜索职位名称" style="width: 100%" v-model="search" @search="searchPeople" @change="changePeople" />
          </div>
          <div class="tit mt12">
            <div class="mr4">*</div>
            <div>选择指定的用工单位进行职位内推，未选择的用工单位无法内推该职位</div>
          </div>
          <div class="tree-item2" style="margin-top:16px;">
            <div>全选当页</div>
            <a-checkbox :checked="isAllSelected" @change="choseAll(treeData)" style="margin-left: 10px;"></a-checkbox>
          </div>
          <div class="employee-selector" style="position:relative;">
            <div v-for="(item, index) in treeData" :key="index">
              <div class="tree-item" :class="item.isSelected ? 'selectStyle' : ''" @click="chose(item, treeData)">
                <div class="tree-item-div">
                  <!-- <img src="@/assets/icons/person1.png" style="width:30px;height:30px;margin-right:10px" /> -->
                  <a-tooltip placement="top">
                    <template slot="title">
                      <span>{{ item.name }}</span>
                    </template>
                    <div class="overflows overflowsWL">
                      {{ item.name }}
                    </div>
                  </a-tooltip>
                </div>
                <span class="checkboxs">
                  <span @click.stop="chose(item, treeData)"></span>
                  <a-checkbox :checked="item.isSelected"></a-checkbox>
                </span>
              </div>
            </div>
          </div>
          <a-pagination
            v-model="current"
            size="small"
            :page-size-options="pageSizeOptions"
            :total="total"
            show-size-changer
            show-less-items
            :page-size="pageSize"
            @showSizeChange="onShowSizeChange"
            @change="onPageChange"
            style="margin-top: 12px; text-align: right;"
          >
            <template slot="buildOptionText" slot-scope="props">
              <span>{{ props.value }}条/页</span>
            </template>
          </a-pagination>
        </div>

        <div class="employee-selector-block2">
          <div class="employee-selector-title">
            <div>
              已经选中 <span class="selectStyle">{{ selectedListTemp.length }}</span>
            </div>
            <a-button type="link" v-if="selectedListTemp.length" @click="remove">
              清除
            </a-button>
          </div>
          <div class="employee-selector">
            <div v-for="(item, i) in selectedListTemp" :key="i" class="employee-selector-item">
              <div class="tree-item">
                <div class="tree-item-div">
                  <!-- <img src="@/assets/icons/person1.png" style="width:30px;height:30px;margin-right:10px" /> -->
                  <a-tooltip placement="top">
                    <template slot="title">
                      <span>{{ item.name }}</span>
                    </template>
                    <div class="overflows overflowsWR">
                      {{ item.name }}
                    </div>
                  </a-tooltip>
                </div>
              </div>
              <img @click="deleteItem(item, i)" src="@/assets/icons/删除.png" style="width:14px;height:14px;cursor: pointer;" />
            </div>
          </div>
        </div>
      </div>
    </a-spin>
    <div class="m-btn">
      <a-button @click="onCancel" class="mr12">上一步</a-button>
      <a-button type="primary" @click="onOk">
        下一步
      </a-button>
    </div>
  </div>
</template>

<script>
import { getCompanies } from "../api";
export default {
  props: {
    selectedList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      search: "",
      spinning: false,
      treeData: [],
      selectedListTemp: [],
      isAllSelected: false,
      pageSizeOptions: ["10", "20", "50", "100"],
      pageSize: 10,
      current: 1,
      total: 50
    };
  },
  created() {
    this.getSelectDepTree("visibleinit");
  },
  mounted() {
    this.selectedListTemp = [];
  },
  methods: {
    // 分页变化
    onPageChange(pageNumber) {
      this.current = pageNumber;
      this.getSelectDepTree();
    },
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize;
      this.current = 1;
      this.getSelectDepTree();
    },
    remove() {
      this.spinning = true;
      for (let i = 0, len = this.treeData.length; i < len; i++) {
        this.treeData[i].isSelected = false;
        this.ergodicAll(this.treeData[i]);
      }
      this.isAllSelected = false;
      setTimeout(() => {
        this.spinning = false;
      }, 10);
    },
    choseAll(data) {
      this.isAllSelected = !this.isAllSelected;
      var that = this;
      this.spinning = true;
      for (var j = 0, len = data.length; j < len; j++) {
        data[j].isSelected = that.isAllSelected;
        that.ergodicAll(data[j]);
      }

      setTimeout(function() {
        that.spinning = false;
      }, "10");
    },
    chose(item, data) {
      item.isSelected = !item.isSelected;
      this.onChange(item);
    },
    onChange(item) {
      this.spinning = true;
      var that = this;
      setTimeout(function() {
        that.ergodic(item);
        that.spinning = false;
      }, "10");
    },
    ergodic(item) {
      if (!item.isSelected) {
        var index = this.selectedListTemp.findIndex(it => it.id === item.id); // 存在再删除，防止删除错误
        if (index !== -1) {
          this.selectedListTemp.splice(index, 1); // 删除
        }
      } else {
        if (this.selectedListTemp.findIndex(it => it.id === item.id) === -1) {
          // 不存在再添加，防止重复添加
          this.selectedListTemp.push(item);
        }
      }
      var count = this.treeData.length;
      var allSelect = true;
      for (var i = 0; i < count; i++) {
        if (!this.treeData[i].isSelected) {
          allSelect = false;
          break;
        }
      }
      this.isAllSelected = allSelect;
    },
    ergodicAll(item) {
      if (!item.isSelected) {
        var index = this.selectedListTemp.findIndex(it => it.id === item.id); // 存在再删除，防止删除错误
        if (index !== -1) {
          this.selectedListTemp.splice(index, 1); // 删除
        }
      } else {
        if (this.selectedListTemp.findIndex(it => it.id === item.id) === -1) {
          // 不存在再添加，防止重复添加
          this.selectedListTemp.push(item);
        }
      }
    },

    // 获取树
    async getSelectDepTree(query) {
      try {
        this.spinning = true;
        const params = {
          pageSize: this.pageSize,
          pageNo: this.current,
          queryType: 1,
          "orders[0].property": "gmtCreate",
          "orders[0].desc": true
        };
        if (query && query !== "visibleinit") {
          params["name"] = this.search;
        }
        const { data } = await getCompanies(params);
        if (data.entities === null) {
          this.$message.warning("暂无数据");
          this.treeData = [];
          this.isAllSelected = false;
        } else {
          this.treeData = this.formatCompanyData(data.entities);
          this.total = data.entityCount;
          let allSelect = true;
          const count = data.entities.length;
          if (count !== 0) {
            if (query && query === "visibleinit") {
              this.selectedList.forEach(e => {
                this.treeData.forEach(m => {
                  if (e.id === m.id) {
                    m.isSelected = true;

                    this.selectedListTemp.push(m);
                  }
                });
              });
            } else {
              this.selectedListTemp.forEach(e => {
                this.treeData.forEach(m => {
                  if (e.id === m.id) {
                    m.isSelected = true;
                  }
                });
              });
            }
            this.treeData.some(e => {
              if (!e.isSelected) {
                allSelect = false;
                return true;
              }
            });

            this.isAllSelected = allSelect;
          } else {
            this.isAllSelected = false;
          }
        }
        this.spinning = false;
      } catch (err) {
        this.spinning = false;
        console.log("error log --> ", err);
      }
    },
    formatCompanyData(company) {
      const parent = [];
      for (var key = 0; key < company.length; key++) {
        var selected = false;

        this.selectedListTemp.forEach((item, index) => {
          if (item.id === company[key].id) {
            selected = true;
          }
        });
        var emp = {};

        emp = {
          id: company[key].id,
          name: company[key].name
        };
        this.selectedListTemp.forEach((item, index) => {
          item.isSelected = true;
        });

        parent.push(emp);
      }
      return parent;
    },
    searchPeople(query) {
      this.selectedKeysBeforeSearch = this.selectedListTemp.map(item => item.id);
      this.getSelectDepTree(query);
    },
    changePeople(e) {
      if (e.target.value === "") {
        this.getSelectDepTree();
        this.selectedKeysBeforeSearch = this.selectedListTemp.map(item => item.id);
      }
    },
    deleteItem(item, index) {
      // this.treeData[index].isSelected = false;
      item.isSelected = false;
      this.treeData.forEach((item2, index2) => {
        if (item2.id === item.id) {
          this.treeData[index2].isSelected = false;
        }
      });
      this.treeData = JSON.parse(JSON.stringify(this.treeData));
      this.spinning = true;

      var that = this;
      setTimeout(function() {
        that.$nextTick(() => {
          that.ergodic(item);
        });

        that.spinning = false;
      }, 100);
    },
    onOk() {
      if (this.selectedListTemp.length === 0) {
        this.$message.warning("请选择用工单位");
        return;
      }
      // if (this.selectedListTemp.length > 50) {
      //   this.$message.success("一次性最多选择50人");
      //   return;
      // }
      const arr = this.selectedListTemp.map(item => {
        return {
          id: item.id,
          name: item.name
        };
      });
      this.$emit("upDate", 2, arr);
    },
    onCancel() {
      this.$emit("upDate", 0);
    }
  }
};
</script>
<style lang="scss" scoped>
.employee-selector {
  height: 346px;
  margin-top: 2px;
  padding-right: 10px;
  overflow: auto;
}
.tit {
  width: 352px;
  font-size: 12px;
  font-weight: 400;
  color: #767885;
  display: flex;
  & > div:nth-child(1) {
    color: #ff7085;
  }
}
.verticalBar {
  width: 1px;
  background: #e8e8e8;
  display: inline-block;
  margin-top: 40px;
  vertical-align: top;
  margin-right: 30px;
  margin-left: 30px;
  html,
  body,
  #app {
    height: 100%;
  }
}
.tree-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  height: 40px;
  .tree-item-div {
    display: flex;
    align-items: center;

    .overflowsWL {
      width: 264px;
    }
    .overflowsWR {
      width: 176px;
    }
    .overflows {
      display: inline-block;
      margin-right: 10px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
.tree-item2 {
  display: flex;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
  margin-bottom: 10px;
}
.employee-selector-wrapper2 {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  .employee-selector-block {
    width: 382px;
    padding-right: 22px;
    .employee-selector-title {
      width: 100%;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
    }
    .employee-selector {
      height: 346px;
      margin-top: 20px;
      padding-right: 20px;
      overflow: auto;
      .employee-selector-item {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
      }
    }
  }
  .employee-selector-block2 {
    width: 274px;
    border-radius: 8px;
    background-color: #f4f6fa;
    padding: 12px 4px 12px 12px;
    .employee-selector-title {
      width: 100%;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
      display: flex;
      justify-content: space-between;
    }
    .employee-selector {
      height: 420px;
      margin-top: 2px;
      padding-right: 10px;
      overflow: auto;
      .employee-selector-item {
        width: 100%;
        height: 40px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
      }
    }
  }
}
.iconStyle {
  font-size: 18px;
  color: var(--primary);
}
.selectStyle {
  color: var(--primary);
}
.checkboxs {
  position: relative;
  & > span {
    position: absolute;
    top: 0;
    left: 0;
    display: block;
    width: 20px;
    height: 20px;
  }
}
.m-btn {
  width: 720px;
  height: 56px;
  border-top: 1px solid #e8e8e8;
  text-align: right;
  padding: 12px 24px 0 0;
  margin: 32px 0 -24px -24px;
}
</style>
